package Meter::Action::ShowMeterings;

#===============================================================================
#     REVISION:  $Id: ShowMeterings.pm 153 2011-08-08 10:13:42Z xdr.box@gmail.com $
#  DESCRIPTION:  Show meterings
#===============================================================================

use strict;
use warnings;

use Readonly;
Readonly our $VERSION => qw($Revision: 153 $) [1];

use English qw( -no_match_vars );
use List::Util qw( min max reduce );

#use Smart::Comments;

use Meter::Log;

use base qw(Meter::Action);

sub generate_page_content {
    my $self = shift;

    my $logger = get_logger();

    my $appartment = $self->{'user'}->appartment();

    if ( !$appartment ) {
        $logger->warn('User has not specified appartment info yet');

        return $self->process_template( 'show_meterings.tt2',
            { meterings => [] } );
    }

    $logger->info( 'Show meterings of user ' . $self->{'user'}->username() );

    my $meterings = [ $appartment->meterings() ];
    return $self->process_template(
        'show_meterings.tt2',
        {   meterings      => $meterings,
            min_start_date => _get_min_start_date($meterings),
            max_end_date   => _get_max_end_date($meterings),
            min_cold_water_start_amount =>
                _get_min_cold_water_start_amount($meterings),
            max_cold_water_end_amount =>
                _get_max_cold_water_end_amount($meterings),
            min_hot_water_start_amount =>
                _get_min_hot_water_start_amount($meterings),
            max_hot_water_end_amount =>
                _get_max_hot_water_end_amount($meterings),
        }
    );
}

sub _get_min_start_date {
    my $meterings = shift;

    return reduce { $a < $b ? $a : $b }
    map { $_->start_date() } @{$meterings};
}

sub _get_max_end_date {
    my $meterings = shift;

    return reduce { $a > $b ? $a : $b }
    map { $_->end_date() } @{$meterings};
}

sub _get_min_cold_water_start_amount {
    my $meterings = shift;

    return min map { $_->cold_water_start_amount() } @{$meterings};
}

sub _get_max_cold_water_end_amount {
    my $meterings = shift;

    return max map { $_->cold_water_end_amount() } @{$meterings};
}

sub _get_min_hot_water_start_amount {
    my $meterings = shift;

    return min map { $_->hot_water_start_amount() } @{$meterings};
}

sub _get_max_hot_water_end_amount {
    my $meterings = shift;

    return max map { $_->hot_water_end_amount() } @{$meterings};
}

1;
